<template>
  <el-config-provider :locale="zhCn">
    <div class="send-social">
      <!-- 筛选条件区域 -->
      <filter-form
        v-model="filterForm"
        :form-items="formItems"
        @search="handleSearch"
        @reset="resetFilter"
        @update:modelValue="handleFilterChange"
        labelWidth="100px"
      />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="success" @click="handleCreateSopTask">新增计划</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="taskList" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="sopTaskName" label="计划名称" min-width="150" />
          <el-table-column prop="taskNumber" label="任务条数" width="100" align="center">
            <template #default="scope"> {{ scope.row.taskNumber }} 个 </template>
          </el-table-column>
          <el-table-column prop="actualDays" label="实际天数" width="100" align="center">
            <template #default="scope"> {{ scope.row.actualDays }} 天 </template>
          </el-table-column>
          <el-table-column prop="marketingPlanStart" label="营销开始时间" width="120" align="center" />
          <el-table-column prop="marketingPlanEnd" label="营销结束时间" width="120" align="center" />
          <el-table-column prop="createByStr" label="创建人" width="100" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEditSopTask(scope.row)">编辑</el-button>
              <el-button type="success" link @click="handleViewDetail(scope.row)">任务</el-button>
              <el-button type="info" link @click="showTimeline(scope.row)">进度</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增任务对话框 -->
      <el-dialog v-model="sopTaskDialogVisible" :title="isEditMode ? '编辑计划' : '新增计划'" width="500px" destroy-on-close>
        <el-form :model="sopTaskForm" label-width="100px" :rules="sopTaskRules" ref="sopTaskFormRef">
          <el-form-item label="计划名称" prop="sopTaskName">
            <el-input v-model="sopTaskForm.sopTaskName" placeholder="请输入计划名称" />
          </el-form-item>
          <el-form-item label="营销时间" prop="timeRange">
            <el-date-picker
              v-model="sopTaskForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              :shortcuts="[
                {
                  text: '最近一周',
                  value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    return [start, end];
                  }
                },
                {
                  text: '最近一个月',
                  value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    return [start, end];
                  }
                },
                {
                  text: '最近三个月',
                  value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    return [start, end];
                  }
                }
              ]"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="sopTaskDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitSopTask">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialogVisible" title="计划详情" width="90%" :destroy-on-close="true" class="detail-dialog">
        <SendSocialDetail v-if="detailDialogVisible" :sop-id="currentTaskId" :task-info="currentTaskInfo" @close="detailDialogVisible = false" />
      </el-dialog>

      <TimelineDialog v-model:visible="timelineDialogVisible" :plan-stats="planStats" :timeline-data="timelineData" />
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import { getSopGroupTaskList, addSopGroupTask, updateSopGroupTask, deleteSopGroupTask, getSopGroupProgress } from '@/api/friendSocial/SOPSocial';
import SendSocialDetail from './SendSocialDetail.vue';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface SopTask {
  sopId: string;
  sopTaskName: string;
  marketingPlanStart: string;
  marketingPlanEnd: string;
  createBy: string;
  createTime: string;
  taskNumber: number;
  actualDays: number;
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

// 筛选表单配置
const formItems = computed<FormItem[]>(() => [
  {
    type: 'input',
    label: '计划名称',
    prop: 'sopTaskName',
    placeholder: '请输入计划名称',
    clearable: true
  },
  {
    type: 'date',
    label: '营销开始时间',
    prop: 'marketingPlanStart',
    placeholder: '请选择营销开始时间',
    valueFormat: 'YYYY-MM-DD',
    dateType: 'date',
    clearable: true
  },
  {
    type: 'date',
    label: '营销结束时间',
    prop: 'marketingPlanEnd',
    placeholder: '请选择营销结束时间',
    valueFormat: 'YYYY-MM-DD',
    dateType: 'date',
    clearable: true
  }
]);

// 筛选表单数据
const filterForm = reactive({
  sopTaskName: '',
  marketingPlanStart: '',
  marketingPlanEnd: ''
});

// 任务列表数据
const taskList = ref<SopTask[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 新增任务对话框
const sopTaskDialogVisible = ref(false);
const sopTaskFormRef = ref();
const sopTaskForm = reactive({
  sopTaskName: '',
  timeRange: [] as string[]
});

// 表单验证规则
const sopTaskRules = {
  sopTaskName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  timeRange: [{ required: true, message: '请选择营销时间', trigger: 'change' }]
};

// 编辑模式相关
const isEditMode = ref(false);
const currentTaskId = ref('');

// 获取wx_id
const wx_id = ref(localStorage.getItem('msgprofile') ? JSON.parse(localStorage.getItem('msgprofile')!).wx_id : '');

// 详情弹窗相关
const detailDialogVisible = ref(false);
const currentTaskInfo = ref<SopTask | null>(null);

// 进度弹窗相关
const timelineDialogVisible = ref(false);
const timelineData = ref<Array<any>>([]);
const planStats = ref({
  totalDays: 0,
  executedDays: 0,
  totalTasks: 0,
  executedTasks: 0
});

const TimelineDialog = defineAsyncComponent(() => import('@/components/common/TimelineDialog.vue'));

onMounted(() => {
  handleSearch();
});

// 搜索方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    const searchData = formData || filterForm;
    const params = {
      sopTaskName: searchData.sopTaskName,
      marketingPlanStart: searchData.marketingPlanStart,
      marketingPlanEnd: searchData.marketingPlanEnd,
      current: currentPage.value,
      size: pageSize.value,
      wxId: wx_id.value
    };
    const res = (await getSopGroupTaskList(params)) as unknown as ApiResponse<{
      records: SopTask[];
      total: number;
    }>;
    if (res.code === 200) {
      taskList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取任务列表失败');
    }
  } catch (e) {
    ElMessage.error('获取任务列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.sopTaskName = '';
  filterForm.marketingPlanStart = '';
  filterForm.marketingPlanEnd = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.sopTaskName = val.sopTaskName || '';
  filterForm.marketingPlanStart = val.marketingPlanStart || '';
  filterForm.marketingPlanEnd = val.marketingPlanEnd || '';
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 修改编辑方法
const handleEditSopTask = (task: SopTask) => {
  isEditMode.value = true;
  currentTaskId.value = task.sopId;
  sopTaskForm.sopTaskName = task.sopTaskName;
  sopTaskForm.timeRange = [task.marketingPlanStart, task.marketingPlanEnd];
  sopTaskDialogVisible.value = true;
};

// 新增计划对话框方法
const handleCreateSopTask = () => {
  isEditMode.value = false;
  currentTaskId.value = '';
  sopTaskForm.sopTaskName = '';
  sopTaskForm.timeRange = [];
  sopTaskDialogVisible.value = true;
};

// 提交计划方法
const submitSopTask = async () => {
  if (!sopTaskFormRef.value) return;

  await sopTaskFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const [marketingPlanStart, marketingPlanEnd] = sopTaskForm.timeRange;
        const taskData = {
          sopTaskName: sopTaskForm.sopTaskName,
          marketingPlanStart,
          marketingPlanEnd,
          createBy: wx_id.value
        };

        let res: ApiResponse;
        if (isEditMode.value) {
          res = (await updateSopGroupTask({
            sopId: currentTaskId.value,
            ...taskData
          })) as unknown as ApiResponse;
        } else {
          res = (await addSopGroupTask(taskData)) as unknown as ApiResponse;
        }

        if (res.code === 200) {
          ElMessage.success(isEditMode.value ? '计划更新成功' : '计划创建成功');
          sopTaskDialogVisible.value = false;
          handleSearch();
        } else {
          throw new Error(res.msg || (isEditMode.value ? '更新计划失败' : '创建计划失败'));
        }
      } catch (e) {
        ElMessage.error(isEditMode.value ? '更新计划失败' : '创建计划失败');
      }
    }
  });
};

// 删除计划
const handleDelete = (task: SopTask) => {
  ElMessageBox.confirm('确定要删除该计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = (await deleteSopGroupTask(task.sopId)) as unknown as ApiResponse;
        if (res.code === 200) {
          ElMessage.success('删除成功');
          handleSearch();
        } else {
          throw new Error(res.msg || '删除失败');
        }
      } catch (e) {
        ElMessage.error('删除失败');
      }
    })
    .catch(() => {});
};

// 查看计划详情方法
const handleViewDetail = (task: SopTask) => {
  currentTaskId.value = task.sopId;
  currentTaskInfo.value = task;
  detailDialogVisible.value = true;
};

// 获取进度方法
const showTimeline = (task: SopTask) => {
  const wxId = wx_id.value;
  const sopId = task.sopId;
  getSopGroupProgress({ wxId, sopId })
    .then((res: any) => {
      const data = res.data || {};
      planStats.value = {
        totalDays: data.actualDays || 0,
        executedDays: data.executedDays || 0,
        totalTasks: data.taskNumber || 0,
        executedTasks: data.executedNumber || 0
      };
      const arr = data.umWechatGroupTask || [];
      timelineData.value = arr.map((item: any) => {
        let statusText = '';
        let type = '';
        let color = '';
        let statusClass = '';
        if (item.status === '2') {
          statusText = '已完成';
          type = 'success';
          color = '#67C23A';
          statusClass = 'remark-success';
        } else if (item.status === '3') {
          statusText = '失败';
          type = 'danger';
          color = '#F56C6C';
          statusClass = 'remark-danger';
        } else if (item.status === '0') {
          statusText = '待发送';
          type = 'warning';
          color = '#E6A23C';
          statusClass = 'remark-warning';
        } else if (item.status === '1') {
          statusText = '进行中';
          type = 'info';
          color = '#409EFF';
          statusClass = 'remark-info';
        } else {
          statusText = '未知';
          type = 'info';
          color = '#909399';
          statusClass = 'remark-unknown';
        }
        return {
          time: item.execution_time,
          content: item.task_name,
          type,
          color,
          user: item.create_by || '',
          remark: statusText,
          statusClass
        };
      });
      timelineDialogVisible.value = true;
    })
    .catch(() => {
      planStats.value = { totalDays: 0, executedDays: 0, totalTasks: 0, executedTasks: 0 };
      timelineData.value = [];
      timelineDialogVisible.value = true;
    });
};
</script>

<style lang="scss" scoped>
.send-social {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.detail-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(90vh - 120px);
    overflow: hidden;
  }
}

:deep(.el-overlay) {
  .detail-dialog {
    --el-dialog-margin-top: 2vh !important;
  }
}
</style>
